<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="滞留件编号" prop="retNumber">
        <el-input
          v-model="queryParams.retNumber"
          placeholder="请输入滞留件编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单编号" prop="orderNumber">
        <el-input
          v-model="queryParams.orderNumber"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="货架编号" prop="shelfNumber">
        <el-input
          v-model="queryParams.shelfNumber"
          placeholder="请输入货架编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仓位编号" prop="positionNumber">
        <el-input
          v-model="queryParams.positionNumber"
          placeholder="请输入仓位编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="上架备注" prop="listNotes">
        <el-input
          v-model="queryParams.listNotes"
          placeholder="请输入上架备注"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户编号" prop="userAccount">
        <el-input
          v-model="queryParams.userAccount"
          placeholder="请输入客户编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="上架时间" prop="onshelfTime">
        <el-date-picker clearable
                        v-model="queryParams.onshelfTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择上架时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="下架时间" prop="overTime">
        <el-date-picker clearable
                        v-model="queryParams.overTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择下架时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="处理状态" prop="handleStatus">
        <el-select v-model="queryParams.handleStatus" placeholder="请选择处理状态" clearable>
          <el-option
            v-for="dict in dict.type.handle_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="销毁时间" prop="destroyTime">
        <el-date-picker clearable
                        v-model="queryParams.destroyTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择销毁时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="retshelfAdd"
          v-hasPermi="['system:retion:add']"
        >滞留件上架</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="retshelfUp"
          v-hasPermi="['system:retion:edit']"
        >滞留件下架</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="single"
          @click="retshelfDest"
          v-hasPermi="['system:retion:edit']"
        >滞留件销毁</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:retion:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:retion:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:retion:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="retionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="滞留件编号" align="center" prop="retNumber" />
      <el-table-column label="订单编号" align="center" prop="orderNumber" />
      <el-table-column label="货架编号" align="center" prop="shelfNumber" />
      <el-table-column label="仓位编号" align="center" prop="positionNumber" />
      <el-table-column label="上架备注" align="center" prop="listNotes" />
      <el-table-column label="客户编号" align="center" prop="userAccount" />
      <el-table-column label="上架时间" align="center" prop="onshelfTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.onshelfTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="下架时间" align="center" prop="overTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.overTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="处理状态" align="center" prop="handleStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.handle_status" :value="scope.row.handleStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="销毁时间" align="center" prop="destroyTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.destroyTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="retshelfUp(scope.row)"
            v-hasPermi="['system:retion:edit']"
          >下架</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:retion:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改滞留件管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="滞留件编号" prop="retNumber">
          <el-input v-model="form.retNumber" placeholder="请输入滞留件编号" :disabled="retSwitch === 2 || retSwitch === 3"/>
        </el-form-item>
        <el-form-item label="订单编号" prop="orderNumber">
          <!--          <el-input v-model="form.orderNumber" placeholder="请输入订单编号" />-->
          <el-select v-model="form.orderNumber" filterable placeholder="请选择" @change="handleClientChange" :disabled="retSwitch === 2 || retSwitch === 3">
            <el-option v-for="item in notInOrder" :key="item.id" :label="item.orderNumber" :value="item.orderNumber" >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="货架编号" prop="shelfNumber">
          <el-input v-model="form.shelfNumber" placeholder="请输入货架编号" :disabled="retSwitch === 2 || retSwitch === 3" />
        </el-form-item>
        <el-form-item label="仓位编号" prop="positionNumber">
          <!--          <el-input v-model="form.positionNumber" placeholder="请输入仓位编号" />-->
          <el-select v-model="form.positionNumber" filterable placeholder="请选择" @change="handleCangChange" :disabled="retSwitch === 2 || retSwitch === 3">
            <el-option v-for="item in zhiLiuCang" :key="item.id" :label="item.positionNumber" :value="item.positionNumber" >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上架备注" prop="listNotes">
          <el-input v-model="form.listNotes" placeholder="请输入上架备注" :disabled="retSwitch === 2 || retSwitch === 3"/>
        </el-form-item>
        <el-form-item label="客户编号" prop="userAccount">
          <el-input v-model="form.userAccount" placeholder="请输入客户编号" :disabled="retSwitch === 2 || retSwitch === 3"/>
        </el-form-item>
        <el-form-item label="上架时间" prop="onshelfTime">
          <el-date-picker clearable
                          v-model="form.onshelfTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择上架时间"
                          :disabled="retSwitch === 2 || retSwitch === 3">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="下架时间" prop="overTime" v-if="retSwitch === 2">
          <el-date-picker clearable
                          v-model="form.overTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择下架时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="处理状态" prop="handleStatus" >
          <el-select v-model="form.handleStatus" placeholder="请选择处理状态">
            <el-option
              v-for="dict in dict.type.handle_status"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
              :disabled="true"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="销毁时间" prop="destroyTime" v-if="retSwitch === 3" >
          <el-date-picker clearable
                          v-model="form.destroyTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择销毁时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="retSwitchCon">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRetion, getRetion, delRetion, addRetion, updateRetion } from "@/api/system/retion";
import {listInfo, updateInfo} from "@/api/system/info";
import {listPosition} from "@/api/system/position";
import {listStore, updateStore} from "@/api/system/store";

export default {
  name: "Retion",
  dicts: ['handle_status'],
  data() {
    return {
      //上架下架销毁控制
      retSwitch: 0,//0-默认 1-上架 2-下架 3-销毁
      // 所有入库表的数据
      allStoreList: [],
      //订单列表
      orderTypeselectoption: [],
      //未入库订单列表
      notInOrder: [],
      //仓位列表
      cangWei: [],
      //滞留仓列表
      zhiLiuCang: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 滞留件管理表格数据
      retionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        retNumber: null,
        orderNumber: null,
        shelfNumber: null,
        positionNumber: null,
        listNotes: null,
        userAccount: null,
        onshelfTime: null,
        overTime: null,
        handleStatus: null,
        destroyTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        retNumber: [
          { required: true, message: "滞留件编号不能为空", trigger: "blur" }
        ],
        orderNumber: [
          { required: true, message: "订单编号不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleCangChange(selectedshelfNumber) {
      // 在选项数组中查找匹配的货架
      const selectedShelf = this.zhiLiuCang.find(
        item => item.positionNumber === selectedshelfNumber
      );

      // 如果找到匹配项则设置客户名称
      if (selectedShelf) {
        this.form.shelfNumber = selectedShelf.shelfNumber;

      }

    },
    handleClientChange(selectedshelfNumber) {
      // 在选项数组中查找匹配的货架
      const selectedShelf = this.notInOrder.find(
        item => item.orderNumber === selectedshelfNumber
      );

      // 如果找到匹配项则设置客户名称
      if (selectedShelf) {
        this.form.userAccount = selectedShelf.userName;
        // this.form.warNumber = selectedShelf.warNumber;
        //   if (selectedShelf.shelfType === 0) {
        //     this.form.positionType = 0;
        //   }
        //   else if (selectedShelf.shelfType === 1){
        //     this.form.positionType = 1;
        //   }
        //   else if (selectedShelf.shelfType === 2){
        //     this.form.positionType = 2;
        //   }
        // } else {
        //   this.form.shelfNumber = ""; // 没有匹配项时清空
      }
    },

    /** 查询滞留件管理列表 */
    getList() {
      this.loading = true;
      listRetion(this.queryParams).then(response => {
        this.retionList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      listInfo().then((res) => {
        this.orderTypeselectoption = res.rows
        this.notInOrder = this.orderTypeselectoption.filter(item => {
          return item.storeStatus === 2;
        });
      });

      listPosition().then((res) => {
        this.cangWei = res.rows
        this.zhiLiuCang = this.cangWei.filter(item => {
          return item.positionType === 2;
        });
      }).catch(error => {
        console.error('获取仓位数据失败:', error);
        this.$message.error('获取仓位数据失败');
      });

      listStore().then(response => {
        this.allStoreList = response.rows; //分页拿数据，而不是全部拿取
      });


    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        retNumber: null,
        orderNumber: null,
        shelfNumber: null,
        positionNumber: null,
        listNotes: null,
        userAccount: null,
        onshelfTime: null,
        overTime: null,
        handleStatus: null,
        destroyTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 上架按钮操作 */
    retshelfAdd() {
      this.reset();
      this.retSwitch = 1;
      this.open = true;
      this.title = "滞留件上架";
    },
    /** 下架按钮操作 */
    retshelfUp(row) {
      this.reset();
      const id = row.id || this.ids
      getRetion(id).then(response => {
        this.form = response.data;
        if(this.form.handleStatus !== 0){
          this.$modal.msgWarning("当前滞留件不可下架");
        }else{
          this.retSwitch = 2;
          this.open = true;
          this.title = "滞留件下架";
        }
      });
    },

    /** 销毁按钮操作 */
    retshelfDest(row){
      this.reset();
      const id = row.id || this.ids
      getRetion(id).then(response => {
        this.form = response.data;
        if(this.form.handleStatus !== 0){
          this.$modal.msgWarning("当前滞留件不可销毁");
        }else{
          this.retSwitch = 3;
          this.open = true;
          this.title = "滞留件销毁";}
      });
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加滞留件管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getRetion(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改滞留件管理";
      });
    },

    retSwitchCon(){
      // 根据 retSwitch 的值调用不同的函数
      switch (this.retSwitch) {
        case 0:
          // this.defaultAction();
          console.warn("默认值：0");
          break;
        case 1:
          this.submitOnForm();
          break;
        case 2:
          this.submitUpForm();
          break;
        case 3:
          this.submitDestroyForm();
          break;
        default:
          console.warn("未知的状态值");
      }
    },

    /** 提交上架按钮 */
    submitOnForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.handleStatus = 0; //0-上架 1-销毁 2-下架
          const tempCreateTime = this.form.createTime;
          addRetion(this.form).then(response => {
            this.$modal.msgSuccess("上架成功");

            //更新订单表
            const selectedOrder = this.orderTypeselectoption.find(
              item => item.orderNumber === this.form.orderNumber
            );
            const orderForm = {
              id: selectedOrder.id,
              orderNumber: selectedOrder.orderNumber,
              orderType: selectedOrder.orderType,
              orderStatus: selectedOrder.orderStatus,
              storeStatus: 0,
              storeTime: tempCreateTime,
              orderCreateTime: selectedOrder.orderCreateTime,

              packStatus: selectedOrder.packStatus,

              outboundStatus: selectedOrder.outboundStatus,
              stocktakingStatus: selectedOrder.stocktakingStatus,
              sendStatus: selectedOrder.sendStatus,
              userName: selectedOrder.userName
            };
            updateInfo(orderForm);

            //更新入库表
            this.allStoreList.forEach((item, index) => {
              console.log(`第${index}个元素:`, item);
              if(item.orderNumber === this.form.orderNumber){
                const Dataform = {
                  id: item.id,
                  warehousing: item.warehousing,
                  orderNumber: item.orderNumber,
                  stockTrackingnumber: item.stockTrackingnumber,
                  commName: item.commName,
                  storeStatus: 0,//订单入库状态 0-全部入库 1-部分入库 2-未入库
                  storeTime: this.form.onshelfTime,//入库时间
                  packageStatus: 1,//0-未入仓 1-已入仓
                  loginAccount: item.loginAccount,
                  orderCreateTime: item.orderCreateTime,
                  userAccount: item.userAccount,
                  userName: item.userName,
                  positionType: 2,//仓位类型  0单件仓位/1组合件仓位/2滞留件仓位
                  positionNumber: this.form.positionNumber//仓位编号
                };
                updateStore(Dataform);
              }
            });

            this.open = false;
            this.getList();
          });

        }
      });
    },

    /** 提交下架按钮 */
    submitUpForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            this.form.handleStatus = 2; //0-上架 1-销毁 2-下架
            updateRetion(this.form).then(response => {
              this.$modal.msgSuccess("下架成功");

              //恢复订单表
              const selectedOrder = this.orderTypeselectoption.find(
                item => item.orderNumber === this.form.orderNumber
              );
              const orderForm = {
                id: selectedOrder.id,
                orderNumber: selectedOrder.orderNumber,
                orderType: selectedOrder.orderType,
                orderStatus: selectedOrder.orderStatus,
                storeStatus: 2,//入库状态 0-全部入库 1-部分入库 2-未入库
                storeTime: null,//入库时间
                orderCreateTime: selectedOrder.orderCreateTime,

                packStatus: selectedOrder.packStatus,

                outboundStatus: selectedOrder.outboundStatus,
                stocktakingStatus: selectedOrder.stocktakingStatus,
                sendStatus: selectedOrder.sendStatus,
                userName: selectedOrder.userName
              };
              updateInfo(orderForm);

              //恢复入库表
              this.allStoreList.forEach((item, index) => {
                if(item.orderNumber === this.form.orderNumber){

                  if(selectedOrder.orderType === 0){//单件
                    const Dataform = {
                      id: item.id,
                      warehousing: item.warehousing,
                      orderNumber: item.orderNumber,
                      stockTrackingnumber: item.stockTrackingnumber,
                      commName: item.commName,
                      storeStatus: 2,//订单入库状态 0-全部入库 1-部分入库 2-未入库
                      storeTime: null,//入库时间
                      packageStatus: 0,//0-未入仓 1-已入仓
                      loginAccount: item.loginAccount,
                      orderCreateTime: item.orderCreateTime,
                      userAccount: item.userAccount,
                      userName: item.userName,
                      positionType: 0,//仓位类型  0单件仓位/1组合件仓位/2滞留件仓位
                      positionNumber: "仓位1"//仓位编号
                    };
                    updateStore(Dataform);
                  }else {//组合件
                    const Dataform = {
                      id: item.id,
                      warehousing: item.warehousing,
                      orderNumber: item.orderNumber,
                      stockTrackingnumber: item.stockTrackingnumber,
                      commName: item.commName,
                      storeStatus: 2,//订单入库状态 0-全部入库 1-部分入库 2-未入库
                      storeTime: null,//入库时间
                      packageStatus: 0,//0-未入仓 1-已入仓
                      loginAccount: item.loginAccount,
                      orderCreateTime: item.orderCreateTime,
                      userAccount: item.userAccount,
                      userName: item.userName,
                      positionType: 1,//仓位类型  0单件仓位/1组合件仓位/2滞留件仓位
                      positionNumber: "仓位2"//仓位编号
                    };
                    updateStore(Dataform);
                  }
                }
              });

              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    //滞留件销毁提交
    submitDestroyForm(){
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            this.form.handleStatus = 1; //0-上架 1-销毁 2-下架
            updateRetion(this.form).then(response => {
              this.$modal.msgSuccess("销毁成功");

              //恢复订单表

              //恢复入库表

              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateRetion(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRetion(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除滞留件管理编号为"' + ids + '"的数据项？').then(function() {
        return delRetion(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/retion/export', {
        ...this.queryParams
      }, `retion_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
